Step 38: CORS

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

If we were to run (or deploy) our Bookmark API and use it in a client application, the browser will block access to the API due to CORS policy.

Since we intend to build a public API, we should add a header to our response, Access-Control-Allow-Origin: *, to allow requests from all domains. To understand how the fix works, go to Postman, run any requests, and notice 7 "header" attributes in the response.

Untitled

Now, stop the API server and install the Node package cors

yarn add cors

Next, update the /src/index.js file by importing cors

import cors from "cors";

Next, linking it to express; this must be done before binding any of the route handlers!

app.use(cors());

That's it! Rerun the server and run any of the API requests in Postman. Make a note of the response header attributes:

Untitled

The cors package adds this Access-Control-Allow-Origin: * to the header of every response we send back to the client. This information informs applications such as browsers that we allow cross-domain requests.

The cors package can take many options to allow, e.g., requests from specific domains (but not all). There are many resources online if you are interested to learn more about this. This short video could be a good starting point: Node API - CORS, what is it and how to use it on YouTube.